package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class CmdGB extends AbstractCmd {

    @Resource
    private GroupService groupService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        String text = update.getMessage().getText();
        String[] cmds = text.split("\n");
        int start = cmds[0].length() + cmds[1].length() + 2;
        String[] groupIdsStr = cmds[1].split("#");
        String msg = text.substring(start);
        for (String groupId : groupIdsStr) {
            try {
                if (StringUtils.isBlank(groupId)) {
                    continue;
                }
                long chatId = Long.parseLong(groupId.trim());
                Group group = groupService.getById(chatId);
                RobotUtils.sendText(group.getTgGroupId(), msg, bot);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getCmdName() {
        return "GB";
    }

    @Override
    public String getDescribe() {
        return "GB                              广播消息给指定的下游群\n";
    }
}
